package com.cjx.print.helper;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.cjx.print.App;
import com.cjx.print.interfaces.Callback;

import java.lang.reflect.Method;
import java.util.Set;

/**
 * create by cjx on 2025/4/21
 * desc:
 */
public class BluetoothHelper {

    private Callback<BluetoothDevice> deviceHandlerCallback;
    private boolean scanAfterOpen = false;

    private final BroadcastReceiver blueToothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
            switch (blueState) {
                case BluetoothAdapter.STATE_ON:
                    if (scanAfterOpen) {
                        log("蓝牙已打开---");
                        startScan();
                    }
                    break;
            }
        }
    };

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @SuppressLint("MissingPermission")
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            //蓝牙发现
            if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                log("蓝牙开始搜索");
            } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                deviceHandlerCallback.callback(device);
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                log("蓝牙搜索结束");
                deviceHandlerCallback.callback(null);
            } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
                log("蓝牙配对状态改变: " + state + ": " + device.getName());
                if (deviceHandlerCallback != null) {
                    deviceHandlerCallback.callback(device);
                }
            } else if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) {
                log("蓝牙请求配对: " + device.getName());
            }
        }
    };

    private static final class HelperHolder {
        static final BluetoothHelper helper = new BluetoothHelper();
    }

    public static BluetoothHelper getInstance() {
        return HelperHolder.helper;
    }

    private BluetoothHelper() {

    }

    // 打开蓝牙
    public boolean openBluetooth() {
        try {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            return bluetoothAdapter.isEnabled() || bluetoothAdapter.enable();
        } catch (Exception e) {
            return false;
        }
    }


    public void closeBluetooth() {
        BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
        if (defaultAdapter.isEnabled()) {
            defaultAdapter.disable();
        }
    }

    public void setDeviceHandlerCallback(Callback<BluetoothDevice> callback) {
        this.deviceHandlerCallback = callback;
    }

    public Set<BluetoothDevice> getBoundDevices() {
        return BluetoothAdapter.getDefaultAdapter().getBondedDevices();
    }

    public void startScan() {
        //注册广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        intentFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
        App.app.registerReceiver(receiver, intentFilter);

        App.app.registerReceiver(blueToothReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));

        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter.isEnabled()) {
            scanAfterOpen = false;
            log("开始扫描");
            bluetoothAdapter.startDiscovery();

        } else {
            log("延迟开始扫描");
            scanAfterOpen = true;
        }
    }

    public void stopScan() {
        log("停止扫描");
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        try {
            App.app.unregisterReceiver(receiver);
        } catch (IllegalArgumentException e) {
            // 接收器未注册
        }
        try {
            App.app.unregisterReceiver(blueToothReceiver);
        } catch (IllegalArgumentException e) {
            // 接收器未注册
        }
    }

    public void bondDevice(String address, String pin, Callback<Boolean> bindCallback) {
        BluetoothDevice bluetoothDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
        // 获取 BluetoothDevice 类的类对象
        Class<?> btClass = BluetoothDevice.class;
        // 获取 createBond 方法的引用
        try {
            Method setPinMethod = BluetoothDevice.class.getMethod("setPin", byte[].class);
            setPinMethod.invoke(bluetoothDevice, pin.getBytes());

            Method createBondMethod = btClass.getMethod("createBond");
            Object result = createBondMethod.invoke(bluetoothDevice);
            log("配对结果：" + result);
            if (result != null) {
                bindCallback.callback((Boolean) result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void log(String message) {
        System.out.println("Bluetooth >>> " + message);
    }
}
